package ch.penas.business.service;

import java.io.Serializable;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.primefaces.event.DateSelectEvent;
import org.primefaces.event.ScheduleEntrySelectEvent;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.LazyScheduleModel;
import org.primefaces.model.ScheduleEvent;
import org.primefaces.model.ScheduleModel;

import ch.penas.business.dom.Agenda;
import ch.penas.business.dom.Formateur;

/** @author Daniel */
public class AgendaServiceImpl extends AgendaAbstractMYSQL implements
		AgendaService, Serializable {

	/** Serialisation de la class pour une question de securiter. */
	private static final long serialVersionUID = -6797092500849314538L;

	private Agenda agenda;

	/** Liste de l,'agenda. */
	private List<Agenda> mAgendaList;

	/** tempsRechercheAgenda est egal a agenda. */
	private Agenda tempsRechercheAgenda = new Agenda();

	/** eventModel est un model d'evenement
	 *  du schedule composant de primefaces. */
	private ScheduleModel eventModel;

	/** lazyEventModel est un model simple d'evenement
	 *  du schedule composant de primefaces. */
	private ScheduleModel lazyEventModel;

	/** event est un evenement du schedule composant de primefaces. */
	private ScheduleEvent event = new DefaultScheduleEvent();

	/** Date d'initialisation (Date du jour). */
	private Date maDate;

	private Date StartDateSelectEvent;

	private boolean isTrue = true;

	/** startHeur. */
	private String startHeur;

	/** Constructeur par défaut de la class AgendaServiceImpl. */
	public AgendaServiceImpl() {
		this.agenda = new Agenda();
		maDate = new Date();
		this.mAgendaList = new ArrayList<Agenda>();
		eventModel = new DefaultScheduleModel();
		lazyEventModel = new LazyScheduleModel();
	}

	@SuppressWarnings("deprecation")
	public final void addEvent(final Agenda mAgenda) {
		if (event.getId() == null) {
			if (getStartHeur().length() == 5) {
				Date eventDate = event.getStartDate();

				String stringtHeur = getStartHeur().
						substring(0, 2);
				int intHeur = Integer.parseInt(stringtHeur);
				eventDate.setHours(intHeur);

				String stringMinute = getStartHeur();
				int separ = stringMinute.indexOf(":");
				String stringMinuteSepar = stringMinute.
						substring(separ + 1).trim();
				int intMinute = Integer.parseInt(
						stringMinuteSepar);
				eventDate.setMinutes(intMinute);

				eventModel.addEvent(new DefaultScheduleEvent(
						event.getTitle(), eventDate,
						event.getStartDate(), false));

				// this.agenda.validate();
				this.agenda.setSalle(mAgenda.getSalle());
				this.agenda.setCommentaire(
						mAgenda.getCommentaire());
				this.agenda.setUser(mAgenda.getUser());
				this.agenda.setTitle(event.getTitle());

				SimpleDateFormat formatter = new
						SimpleDateFormat("dd-MM-yyyy");
				String dateFormatter = formatter.format(
						event.getStartDate());
				String b = dateFormatter.substring(6, 10) + '/'
						+ dateFormatter.substring(3, 5)
						+ '/'
						+ dateFormatter.substring(0, 2);

				this.agenda.setStartDate(b);

				this.agenda.setStartHeur(event.getStartDate());
				this.add(this.agenda);

			} else if (getStartHeur().length() == 4) {
				Date eventDate = event.getStartDate();

				String stringtHeur = getStartHeur().
						substring(0, 1);
				int intHeur = Integer.parseInt(stringtHeur);
				eventDate.setHours(intHeur);

				String stringMinute = getStartHeur();
				int separ = stringMinute.indexOf(":");
				String stringMinuteSepar = stringMinute.
						substring(separ + 1)
						.trim();
				int intMinute = Integer.
						parseInt(stringMinuteSepar);
				eventDate.setMinutes(intMinute);

				eventModel.addEvent(new DefaultScheduleEvent(
						event.getTitle(), eventDate,
						event.getStartDate(), false));

				// this.agenda.validate();
				this.agenda.setSalle(mAgenda.getSalle());
				this.agenda.setCommentaire(
						mAgenda.getCommentaire());
				this.agenda.setUser(mAgenda.getUser());
				this.agenda.setTitle(event.getTitle());

				SimpleDateFormat formatter = new
						SimpleDateFormat("dd-MM-yyyy");
				String dateFormatter = formatter.format(
						event.getStartDate());
				String b = dateFormatter.substring(6, 10) + '/'
						+ dateFormatter.substring(3, 5)
						+ '/'
						+ dateFormatter.substring(0, 2);

				this.agenda.setStartDate(b);
				this.agenda.setStartHeur(event.getStartDate());
				this.add(this.agenda);
			}
		} else {
			if (getStartHeur().length() == 5) {
			System.out.println("JE SUIS RENTRER DANS L'UPDATE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!   (TAILLE ====5)");
			Date eventDate = event.getStartDate();

			String stringtHeur = getStartHeur().substring(0, 2);
			int intHeur = Integer.parseInt(stringtHeur);
			eventDate.setHours(intHeur);

			String stringMinute = getStartHeur();
			int separ = stringMinute.indexOf(":");
			String stringMinuteSepar = stringMinute.
					substring(separ + 1).trim();
			int intMinute = Integer.parseInt(stringMinuteSepar);
			eventDate.setMinutes(intMinute);

			eventModel.updateEvent(event);
			this.agenda.setIdPlanning(mAgenda.getIdPlanning());
			this.agenda.setUser(mAgenda.getUser());
			this.agenda.setTitle(event.getTitle());
			SimpleDateFormat formatter = new
					SimpleDateFormat("dd-MM-yyyy");
			String dateFormatter = formatter.format(
					event.getStartDate());
			String b = dateFormatter.substring(6, 10) + '/'
					+ dateFormatter.substring(3, 5)
					+ '/'
					+ dateFormatter.substring(0, 2);
			this.agenda.setStartDate(b);
			this.agenda.setStartHeur(eventDate);
			this.agenda.setSalle(mAgenda.getSalle());
			this.agenda.setCommentaire(mAgenda.getCommentaire());
			event = new DefaultScheduleEvent();
			this.update(this.agenda);

		} else if ((getStartHeur().length() == 4) || (mAgenda.getIdPlanning() != "")) {
			System.out.println("JE SUIS RENTRER DANS "
		+
					"L'UPDATE !!!!!!!!!!!!"
					+
					"!!!!!!!!!!!!!!!!!!!!!"
					+
					"!!!!!!!!!!!!!!!!!!!!"
					+
					"!!!!!!!!!!   (TAILLE ====4)");
			Date eventDate = event.getStartDate();
			
			String stringtHeur = getStartHeur().substring(0, 1);
			int intHeur = Integer.parseInt(stringtHeur);
			eventDate.setHours(intHeur);

			String stringMinute = getStartHeur();
			int separ = stringMinute.indexOf(":");
			String stringMinuteSepar = stringMinute.
					substring(separ + 1).trim();
			int intMinute = Integer.parseInt(stringMinuteSepar);
			eventDate.setMinutes(intMinute);

			eventModel.updateEvent(event);
			this.agenda.setIdPlanning(mAgenda.getIdPlanning());
			this.agenda.setUser(mAgenda.getUser());
			this.agenda.setTitle(event.getTitle());
			SimpleDateFormat formatter = new
					SimpleDateFormat("dd-MM-yyyy");
			String dateFormatter = formatter.format(
					event.getStartDate());
			String b = dateFormatter.substring(6, 10) + '/'
					+ dateFormatter.substring(3, 5)
					+ '/'
					+ dateFormatter.substring(0, 2);
			this.agenda.setStartDate(b);
			this.agenda.setStartHeur(eventDate);
			this.agenda.setSalle(mAgenda.getSalle());
			this.agenda.setCommentaire(mAgenda.getCommentaire());
			this.update(this.agenda);
			event = new DefaultScheduleEvent();
		}
		}
	}

	public final List<Agenda> getAll() {
		try {
			initFixture();
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.mAgendaList.removeAll(mAgendaList);
		getEntityTransaction().begin();

		Query query = getEntityManager().createQuery(
				"SELECT e FROM Agenda e");

		@SuppressWarnings("unchecked")
		List<Agenda> b = query.getResultList();
		for (Agenda a : b) {
			//eventModel.addEvent(new DefaultScheduleEvent(a.getTitle(), getMaDate(),getMaDate(), false));
			this.tempsRechercheAgenda = a;
			this.addRecherche(this.getTempsRechercheAgenda());
		}

		getEntityTransaction().commit();

		try {
			closeEntityManager();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return this.mAgendaList;
	}

	public final void add(final Agenda agenda) {
		try {
			initFixture();

			getEntityTransaction().begin();
			getEntityManager().persist(agenda);
			getEntityTransaction().commit();

			closeEntityManager();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public final void update(final Agenda mAgenda) {
		try {
			initFixture();

			getEntityTransaction().begin();
			Agenda genre = getEntityManager().find(
			Agenda.class, mAgenda.getIdPlanning());

			if (mAgenda.getUser() != "") {
				genre.setUser(mAgenda.getUser());
			}
			if (mAgenda.getTitle() != "") {
				genre.setTitle(mAgenda.getTitle());
			}
			System.out.println("JE SUIS LA DATE CHANGERRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR"+mAgenda.getStartDate());
			if (mAgenda.getStartDate() != "") {
				System.out.println("JE SUIS LA DATE CHANGERRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR"+mAgenda.getStartDate());
				genre.setStartDate(mAgenda.getStartDate());
			}
			if (mAgenda.getStartHeur() != "") {
				SimpleDateFormat formatter = new
						SimpleDateFormat("HH:mm");
				Date s = formatter.parse(
						mAgenda.getStartHeur());
				genre.setStartHeur(s);
			}
			if (mAgenda.getSalle() != "") {
				genre.setSalle(mAgenda.getSalle());
			}
			if (mAgenda.getCommentaire() != "") {
				genre.setCommentaire(mAgenda.getCommentaire());
			}
			getEntityTransaction().commit();

			closeEntityManager();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/** Permet de recuperer la valeur de l'eventModel.
	 *
	 * @return eventModel est egal a un evenement du schedule
	 */
	@SuppressWarnings("deprecation")
	public final ScheduleModel getEventModel() {
		if (this.getIsTrue()) {
		try {
			initFixture();
		} catch (Exception e) {
			e.printStackTrace();
		}
		eventModel.clear();
		getEntityTransaction().begin();

		Query query = getEntityManager().createQuery(
				"SELECT e FROM Agenda e");
		System.out.println(query.getResultList());
		@SuppressWarnings("unchecked")
		List<Agenda> queryAgenda = query.getResultList();
		for (Agenda a : queryAgenda) {
			String as = new String("-");
			String das = new String("/");
			String bla = a.getStartDate();
			String str = bla.replace(as, das);
			SimpleDateFormat formatter = new
						SimpleDateFormat("yyyy/MM/dd");
			Date s;
			try {
				if (a.getStartHeur().length() == 8) {
					s = formatter.parse(str);
					String p = a.getStartHeur().
							substring(0, 2);
					int g = Integer.parseInt(p);
					s.setHours(g);

					String pa = a.getStartHeur().
							substring(3, 5);
					int pas = Integer.parseInt(pa);
					s.setMinutes(pas);

					eventModel.addEvent(new
							DefaultScheduleEvent(
							a.getTitle(),
							s, s, false));
				} else {
					s = formatter.parse(str);
					String p = a.getStartHeur().
							substring(0, 1);
					int g = Integer.parseInt(p);
					s.setHours(g);

					eventModel.addEvent(new
							DefaultScheduleEvent(
							a.getTitle(),
							s, s, false));
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		getEntityTransaction().commit();

		try {
			closeEntityManager();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		this.setIsTrue(false);
		}
		return eventModel;
	}

	public final void addRecherche(final Agenda sesultQuery2) {
		this.mAgendaList.add(sesultQuery2);
	}

	public final Agenda getTempsRechercheAgenda() {
		return this.tempsRechercheAgenda;
	}

	/** Permet de selectioner un evenement du schedule.
	 *
	 * @param aSelectEvent est egale a ScheduleEntrySelectEvent
	 */
	public final void onEventSelect(final
			ScheduleEntrySelectEvent aSelectEvent) {
		event = aSelectEvent.getScheduleEvent();
		this.setIsTrue(false);
	}

	/** Permet de selectioner une date du schedule.
	 *
	 * @param aSelectEvent
	 *            est egale a DateSelectEvent
	 */
	public final void onDateSelect(final DateSelectEvent aSelectEvent) {
		setStartDateSelectEvent(aSelectEvent);
		event = new DefaultScheduleEvent("", getStartDateSelectEvent(),
				    getStartDateSelectEvent());
	}

	/** Permet de convertire un String en date.
	 *
	 * @param aDate est egal au String doner en paramettre a la methode
	 * @return la date de aDate convertie en date
	 * @throws ParseException gere l'exception
	 */
	public static Date stringToDate(
			final String aDate) throws ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
		return formatter.parse(aDate);
	}

	/** Permet de modifier la valeur de eventModel.
	 *
	 * @param aEventModel est egale a eventModel du schedule
	 */
	public final void setEventModel(final ScheduleModel aEventModel) {
		this.eventModel = aEventModel;
	}

	/** Permet de recuperer la valeur de lazyEventModel.
	 *
	 * @return lazyEventModel du schedule
	 */
	public final ScheduleModel getLazyEventModel() {
		return lazyEventModel;
	}

	/** Permet de modifier la valeur de lazyEventModel.
	 *
	 * @param aLazyEventModel est egal a lazyEventModel
	 */
	public final void setLazyEventModel(
			final ScheduleModel aLazyEventModel) {
		this.lazyEventModel = aLazyEventModel;
	}

	/** Permet de recuperer la valeur de l'event.
	 *
	 * @return event du schedule
	 */
	public final ScheduleEvent getEvent() {
		return event;
	}

	/** Permet de modifier la valeur de l'event.
	 *
	 * @param aEvent est egale a event
	 */
	public final void setEvent(final ScheduleEvent aEvent) {
		this.event = aEvent;
	}

	/** Permet de recupéré la date (la date du jour).
	 *
	 * @return maDate qui est egale a la date du jour
	 */
	public final Date getMaDate() {
		return this.maDate;
	}

	/** Permet de modifier la valeur de ma date.
	 *
	 * @param aMaDate est egal a maDate
	 */
	public final void setMaDate(final Date aMaDate) {
		this.maDate = aMaDate;
	}

	/**  Permet de recupéré l'Event selectioner.
	 *
	 * @return StartDateSelectEvent
	 */
	public final Date getStartDateSelectEvent() {
		return StartDateSelectEvent;
	}

	/** Permet de modifier la valeur de l'event selectioner.
	 *
	 * @param aStartDateSelectEvent est egal a l'event selectioner
	 */
	@SuppressWarnings("deprecation")
	public final void setStartDateSelectEvent(
			final DateSelectEvent aStartDateSelectEvent) {
		Date date = aStartDateSelectEvent.getDate();
		date.setDate(date.getDate() + 1);
		StartDateSelectEvent = date;
	}

	/**  Permet de recupéré l'heur.
	 *
	 * @return startHeur est egal a l'heur
	 */
	public final String getStartHeur() {
		return startHeur;
	}

	/** Permet de modifier la valeur de l'heur.
	 *
	 * @param aStartHeur est egal a l'heur
	 */
	public final void setStartHeur(final String aStartHeur) {
		this.startHeur = aStartHeur;
	}

	/** Permet de recupéré isTrue.
	 *
	 * @return isTrue est egale a isTrue
	 */
	public final boolean getIsTrue() {
		return isTrue;
	}
	/** Permet de modifier la valeur de isTrue.
	 *
	 * @param aIsTrue est egale a isTrue
	 */
	public final void setIsTrue(final boolean aIsTrue) {
		this.isTrue = aIsTrue;
	}
}